package ar.edu.unq.tpi.uis.tepe3.wicket.model;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import ar.edu.unq.tpi.uis.tepe3.dominio.Group;
import ar.edu.unq.tpi.uis.tepe3.dominio.User;
import ar.edu.unq.tpi.uis.tepe3.persistencia.GroupDAO;
import ar.edu.unq.tpi.uis.tepe3.persistencia.HibernateUtil;

public class GroupList {
	
	private Long id;
	private String name;
	private List<Group> result;
	
	public GroupList(){
		super();
		this.loadAllGroups();
	}
	
	public GroupList(List<Group> grupos){
		super();
		this.result = grupos;
	}
	
	public void search() {
		this.result = this.getGroupDAO().findByExample(this.getExample());
		this.getGroupDAO().flush();
	}

	protected Group getExample() {
		return new Group(this.getName());
	}

	public void clean() {
		this.result.clear();
	}

	public void add(Group group) {
		//Videoclub.getHome(Socio.class).agregar(socio);
		//this.search();
	}
	
	public void loadAllGroups(){
		Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = null;
		try {
			tx = sess.beginTransaction();
			this.result  = sess.createCriteria(Group.class).list();
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally{
			if (sess.isOpen()) sess.close();
		}
	}

	public void delete(Group group) {
		Session sess = HibernateUtil.getSessionFactory().openSession();
		try{
			sess.beginTransaction();
			sess.refresh(group);
			sess.delete(group);
			sess.getTransaction().commit();
			this.result.remove(group);
		} catch(Exception e){
			sess.getTransaction().rollback();
		}finally{
			if (sess.isOpen()) sess.close();
		}
	}

	public GroupDAO getGroupDAO() {
		return new GroupDAO();
	}
	
	//********************
	// GETTERS Y SETTERS
	//********************

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<Group> getResult() {
		return this.result;
	}

	public void setResult(List<Group> groups) {
		this.result = groups;
	}

	
	
}
